<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!-- 搜索框与添加区 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <div>
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              class="input-with-select"
              clearable
              @clear="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="popUp = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#" width="70"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="250">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="250">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="250">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="250">
        </el-table-column>
        <!-- 状态栏 -->
        <el-table-column label="状态" width="250" prop="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#329cff"
              inactive-color="#ff4949"
              @change="alterState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作栏 -->
        <el-table-column label="操作" class="operation">
          <template slot-scope="scope">
            <!-- 修改用户按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="showEditDiaLog(scope.row)"
                size="small"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
              ><el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="deleteUser(scope.row.id)"
              ></el-button
            ></el-tooltip>
            <!-- 编辑权限按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="权限编辑"
              placement="top"
              :enterable="false"
              ><el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="rightControl(scope.row)"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码下标 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[2, 5, 10, 20]"
          :current-page="queryInfo.pagenum"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 注册用户弹出表单 -->
    <el-dialog
      title="注册用户"
      :visible.sync="popUp"
      width="30%"
      @close="clearPopUpValidate"
    >
      <el-form
        :model="ruleForm"
        :rules="foundRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="registerName">
          <el-input v-model="ruleForm.registerName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="registerPassword">
          <el-input v-model="ruleForm.registerPassword"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="registerEmal">
          <el-input v-model="ruleForm.registerEmal"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="registerMobie">
          <el-input v-model="ruleForm.registerMobie"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearPopUpValidate">取 消</el-button>
        <el-button type="primary" @click="addNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹出表单 -->
    <el-dialog
      title="修改用户"
      :visible.sync="amendUp"
      width="30%"
      @close="clearAmenUpValidate"
    >
      <el-form
        :model="ruleForm"
        :rules="amendRules"
        ref="amendPop"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="ruleForm.registerName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="registerEmal">
          <el-input v-model="ruleForm.registerEmal"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="registerMobie">
          <el-input v-model="ruleForm.registerMobie"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearAmenUpValidate">取 消</el-button>
        <el-button type="primary" @click="amend">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户角色弹出表单 -->
    <el-dialog
      title="编辑用户角色"
      :visible.sync="centerDialogVisible"
      width="30%"
    >
      <div class="dialogInnerP">
        <p>当前的用户: {{ userListInfo.username }}</p>
        <p>当前的角色: {{ userListInfo.role_name }}</p>
        <p>
          分配的新角色:
          <el-select
            v-model="userListInfo.picthUserRoleIdList"
            placeholder="请选择"
          >
            <el-option
              v-for="item in userListInfo.userRoleNameList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyRoleType">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      // 控制注册用户弹出表单
      popUp: false,
      // 控制修改用户弹出表单
      amendUp: false,
      // 控制编辑用户弹出表单
      centerDialogVisible: false,
      userList: [],
      total: 0,
      // 弹出表单验证数据
      ruleForm: {
        registerName: "",
        registerPassword: "",
        registerEmal: "",
        registerMobie: "",
        registerId: "",
      },
      // 编辑用户弹出表单数据
      userListInfo: {
        username: "",
        role_name: "",
        id: 0,
        userRoleNameList: [],
        picthUserRoleIdList: "",
      },

      // 注册用户弹出表单数据验证规则
      foundRules: {
        registerName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { whitespace: true, message: "只存在空格", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        registerPassword: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { whitespace: true, message: "只存在空格", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        registerEmal: [
          { required: false, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "不是一个可用的邮箱",
            trigger: "blur",
          },
        ],
        registerMobie: [
          { required: false, message: "请输入电话", trigger: "blur" },
          {
            pattern: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
            message: "请输入正确的号码",
            trigger: "blur",
          },
        ],
      },
      // 修改用户弹出表单数据验证规则
      amendRules: {
        registerEmal: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "不是一个可用的邮箱",
            trigger: "blur",
          },
        ],
        registerMobie: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            pattern: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
            message: "请输入正确的号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  // 加载先获取一次表单数据
  created() {
    this.getUserList();
  },
  methods: {
    // 获取数据列表请求
    async getUserList() {
      const { data: res } = await this.$http({
        method: "get",
        url: "/users",
        params: {
          ...this.queryInfo,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      } else {
        this.userList = res.data.users;
        this.total = res.data.total;
      }
    },
    // 修改用户数据预加载
    async showEditDiaLog(row) {
      const { data: res } = await this.$http({
        url: `/users/${row.id}`,
        method: "get",
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.amendUp = true;
      this.ruleForm.registerId = res.data.id;
      this.ruleForm.registerName = res.data.username;
      this.ruleForm.registerEmal = res.data.email;
      this.ruleForm.registerMobie = res.data.mobile;
    },
    // 修改用户数据
    amend() {
      this.$refs.amendPop.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http({
          method: "put",
          url: `/users/${this.ruleForm.registerId}`,
          data: {
            email: this.ruleForm.registerEmal,
            mobile: this.ruleForm.registerMobie,
          },
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.clearAmenUpValidate();
          this.getUserList();
          return this.$message.success(res.meta.msg);
        }
      });
    },
    // 切换每页显示数据
    handleSizeChange(newsSize) {
      this.queryInfo.pagesize = newsSize;
      this.getUserList();
    },
    // 切换当前页数
    handleCurrentChange(newsPage) {
      this.queryInfo.pagenum = newsPage;
      this.getUserList();
    },
    // 清除注册用户验证错误数据
    clearPopUpValidate() {
      this.popUp = false;
      this.$refs.ruleForm.resetFields();
      this.ruleForm = {
        registerName: "",
        registerPassword: "",
        registerEmal: "",
        registerMobie: "",
        registerId: "",
      };
    },
    clearAmenUpValidate() {
      this.amendUp = false;
      this.$refs.amendPop.resetFields();
      this.ruleForm = {
        registerName: "",
        registerPassword: "",
        registerEmal: "",
        registerMobie: "",
        registerId: "",
      };
    },
    // 修改用户状态
    async alterState(row) {
      console.log(row.id);
      const { data: res } = await this.$http({
        method: "put",
        url: `users/${row.id}/state/${row.mg_state}`,
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
    },
    // 添加用户
    addNewUser() {
      // 检查是否通过验证
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const {
          registerName: username,
          registerPassword: password,
          registerEmal: email,
          registerMobie: mobile,
        } = this.ruleForm;
        const { data: res } = await this.$http({
          method: "post",
          url: "/users",
          data: {
            username,
            password,
            email,
            mobile,
          },
        });
        if (res.meta.status !== 201) {
          this.clearPopUpValidate();
          this.popUp = false;
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("注册成功");
        this.getUserList();
        this.clearPopUpValidate();
        this.popUp = false;
      });
    },
    //删除用户
    async deleteUser(deleteId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") return this.$message.info("已取消删除");
      // 调用接口删除用户
      const { data: res } = await this.$http.delete(`users/${deleteId}`);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.getUserList();
        return this.$message.success(res.meta.msg);
      }
    },
    // 修改用户权限弹出表单
    async rightControl(currentRole) {
      // 弹框前清除上次选择的内容
      this.userListInfo.picthUserRoleIdList = "";
      this.userListInfo.username = currentRole.username;
      this.userListInfo.role_name = currentRole.role_name;
      this.userListInfo.id = currentRole.id;
      const { data: res } = await this.$http({
        url: "roles",
        method: "get",
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userListInfo.userRoleNameList = res.data;
      this.centerDialogVisible = true;
    },
    // 提交用户角色修改
    async modifyRoleType() {
      if (this.userListInfo.picthUserRoleIdList == "") {
        return this.$message.error("未选中数据");
      }
      const { data: res } = await this.$http({
        url: `users/${this.userListInfo.id}/role`,
        method: "put",
        data: {
          rid: this.userListInfo.picthUserRoleIdList,
        },
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getUserList();
      this.$message.success(res.meta.msg);
      this.centerDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 10px;
}
.operation {
  .el-button {
    margin-right: 115px !important;
  }
}
.block {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
.dialogInnerP {
  > p {
    margin-top: 20px;
  }
}
</style>
